/*
 * Copyright (C) 2012 JiangHongTiao
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sk.lieskove.jianghongtiao.paris.core.classify;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import org.apache.log4j.Logger;
import sk.lieskove.jianghongtiao.common.utils.PropertiesUtils;
import sk.lieskove.jianghongtiao.paris.core.persistence.ClassifierStatistics;
import sk.lieskove.jianghongtiao.paris.core.persistence.EvaluatorTestStatistics;
import sk.lieskove.jianghongtiao.paris.core.persistence.TestSet;
import sk.lieskove.jianghongtiao.paris.core.persistence.TestSetClassificationStorage;
import sk.lieskove.jianghongtiao.paris.core.persistence.TrainSet;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.meta.AttributeSelectedClassifier;
import weka.classifiers.meta.FilteredClassifier;
import weka.core.Instance;
import weka.core.Instances;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Remove;

/**
 * 
 * @author xjuraj e-mail: jjurco.sk_gmail.com
 */
public class ThreadClassifier extends Thread implements Serializable {

    private transient Logger log = Logger.getLogger(ThreadClassifier.class);
    private transient PropertiesUtils pu = new PropertiesUtils(ThreadClassifier.class);
    private Classifier classifier;
    private Instances trainInstances;
    private Instances testInstances;
    private Evaluation evaluation;
    private TestSet testSet;
    private ClassifierStatistics classifierStatistics;
    private EvaluatorTestStatistics evaluatorTestStatistics;
    private Timestamp computationTime;

    public ThreadClassifier(Classifier classifier, Instances trainInstances,
            Instances testInstances, Evaluation evaluation,
            TestSet testSet, TrainSet trainSet, String name, String classificationGroup,
            Timestamp classificationTime) {
        super(name);
        if (classifier == null) {
            throw new NullPointerException("Classifier was null! Thread name: " + name);
        }
        if (trainInstances == null) {
            throw new NullPointerException("Train instances was null! Thread name: " + name);
        }
        if (testInstances == null) {
            throw new NullPointerException("Test instances was null! Thread name: " + name);
        }
        if (evaluation == null) {
            throw new NullPointerException("Evaluation was null! Thread name: " + name);
        }
        this.classifier = classifier;
        this.trainInstances = trainInstances;
        this.testInstances = testInstances;
        this.evaluation = evaluation;
        this.testSet = testSet;
        classifierStatistics = new ClassifierStatistics(classifier, trainSet, 
                classificationGroup, classificationTime);
    }

    @Override
    public void run() {
        Timestamp actualTime = new Timestamp((new Date()).getTime());
        log.debug("Running classification for: " + getName() + " at: " + actualTime.toString());
        long start = System.currentTimeMillis();
        try {
//            FilteredClassifier fc = new FilteredClassifier();
//            Remove r = new Remove();
//            r.setAttributeIndices("first");
//            fc.setFilter(r);
//            fc.setClassifier(classifier);
//            fc.buildClassifier(trainInstances);
            classifier.buildClassifier(trainInstances);
        } catch (Exception ex) {
            log.error("Cannot train classifier! Thread: " + getName()
                    + "\tClassifier: " + classifier.toString());
        }
        try {
            for (int i = 0; i < testInstances.size(); i++) {
//                Instance in   = (Instance) testInstances.instance(i);
                Instance instance = (Instance) testInstances.instance(i);
//                instance.setDataset(null);
//                instance.deleteAttributeAt(0);
                
                double evalResult = evaluation.evaluateModelOnceAndRecordPrediction(
                        classifier, instance);
                String evalClass = testSet.getClasses()[(int) evalResult];
                
                TestSetClassificationStorage tscs = getClassificationStorage(instance);
                tscs.setClassifiedClass(evalClass);
            }
        } catch (Exception ex) {
            log.error("Cannot test classifier! Thread: " + getName()
                    + "\tClassifier: " + classifier.toString(), ex);
        }
        this.computationTime = new Timestamp(System.currentTimeMillis() - start);
        evaluatorTestStatistics = new EvaluatorTestStatistics(evaluation, 
                classifierStatistics, testSet, this.computationTime);
        classifierStatistics.setEvaluatorTestStatistics(evaluatorTestStatistics);
    }

    public ClassifierStatistics getClassifierStatistics() {
        return classifierStatistics;
    }

    public EvaluatorTestStatistics getEvaluatorTestStatistics() {
        return evaluatorTestStatistics;
    }

    public Classifier getClassifier() {
        return classifier;
    }

    public Evaluation getEvaluation() {
        return evaluation;
    }

    private TestSetClassificationStorage getClassificationStorage(Instance instance) {
        for (TestSetClassificationStorage tscs : testSet.getTestSetClassificationStorage()) {
            double lId = (double) tscs.getClassificationStorage().getId();
            if (lId == instance.value(0)) {
                return tscs;
            }
        }
        return null;
    }
}
